import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter_card_swiper/flutter_card_swiper.dart';
import 'package:like_button/like_button.dart';
import 'package:meco/views/me/me/controller.dart';
import 'index.dart';
import 'widgets/index.dart';

class HomePage extends GetView<HomeController> {
  const HomePage({super.key});

  // 主视图
  Widget _buildView() {
    return SafeArea(
      child: LayoutBuilder(
        builder: (context, constraints) {
          return SingleChildScrollView(
            child: ConstrainedBox(
              constraints: BoxConstraints(minHeight: constraints.maxHeight),
              child: Padding(
                padding: EdgeInsets.only(top: 20.h, left: 20.w, right: 20.w),
                child: Column(
                  children: [
                    Text(
                      'porcelain',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20.sp,
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                    SizedBox(height: 20.h),
                    _buildCeramicCardCarousel(),
                    SizedBox(height: 18.h),
                    _buildUserCard(),
                    SizedBox(height: 28.h),
                    _buildCeramicRecommend(),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  // 陶瓷推荐
  Widget _buildCeramicRecommend() {
    return Column(
      children: [
        Align(
          alignment: Alignment.topLeft,
          child: Text(
            'Ceramic Recommendation',
            style: TextStyle(
              color: Colors.white,
              fontSize: 20.sp,
              fontWeight: FontWeight.w400,
            ),
          ),
        ),
        SizedBox(height: 16.h),
        Obx(() {
          if (controller.officialContents.isEmpty) {
            return Center(
              child: Container(
                height: 100.h,
                alignment: Alignment.center,
                child: CircularProgressIndicator(color: Colors.white),
              ),
            );
          }

          // 官方内容项
          return GridView.builder(
            shrinkWrap: true,
            physics: NeverScrollableScrollPhysics(), // 禁用GridView自身的滚动
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2, // 两列
              crossAxisSpacing: 10.w,
              mainAxisSpacing: 10.h,
              childAspectRatio: 182 / 244,
            ),
            itemCount: controller.officialContents.length,
            itemBuilder: (context, index) {
              final content = controller.officialContents[index];
              return OfficialContentItem(
                content: content,
                onTap: () {
                  // 跳转到官方页面，并传递内容参数
                  Get.toNamed(Routes.official, arguments: content);

                  // 检查用户是否登录，如果登录则记录浏览
                  final UserService userService = Get.find<UserService>();
                  if (userService.isLoggedIn.value && content.id != null) {
                    // 用户已登录，记录浏览
                    final BrowseRecordRepository repository =
                        BrowseRecordRepository();
                    repository.addBrowseRecord(
                      BrowseRecord(
                        userId: userService.currentUser.value!.id!,
                        contentId: content.id!,
                        type: BrowseType.officialContent,
                        browseTime: DateTime.now(),
                      ),
                    );
                  }
                },
              );
            },
          );
        }),
      ],
    );
  }

  // 用户卡片
  Widget _buildUserCard() {
    return Obx(() {
      if (controller.timerUsers.isEmpty) {
        return SizedBox(height: 66.h);
      }

      // 获取所有用户
      final displayUsers = List<Map<String, dynamic>>.from(
        controller.timerUsers,
      );

      // 定义不同的卡片渐变颜色，只使用两种
      final List<List<Color>> cardGradients = [
        [const Color(0xFF2D5FB6), const Color(0xFF2C59A7)],
        [const Color(0xFF14489A), const Color(0xFF14489A)],
      ];

      return SizedBox(
        height: 66.h,
        child: Column(
          children: [
            Expanded(
              child: CardSwiper(
                key: ValueKey('user_card_swiper_${displayUsers.length}'),
                controller: controller.cardSwiperController,
                cardsCount: displayUsers.length,
                cardBuilder: (
                  context,
                  index,
                  percentThresholdX,
                  percentThresholdY,
                ) {
                  try {
                    final userData = displayUsers[index];
                    final user = userData['user'] as User;

                    // 确定卡片颜色索引，取余确保不会越界
                    final colorIndex = index % cardGradients.length;

                    return Container(
                      key: ValueKey('user_card_${user.id}_$index'),
                      width: double.infinity,
                      height: 66.h,
                      decoration: ShapeDecoration(
                        gradient: LinearGradient(
                          begin: const Alignment(0.00, 0.50),
                          end: const Alignment(1.00, 0.50),
                          colors: cardGradients[colorIndex],
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(34),
                        ),
                      ),
                      child: Row(
                        children: [
                          SizedBox(width: 6.w),
                          GestureDetector(
                            onTap: () {
                              // 先尝试删除已存在的MeController实例，再跳转
                              try {
                                if (Get.isRegistered<MeController>()) {
                                  Get.delete<MeController>(force: true);
                                }
                              } catch (e) {
                                print('删除MeController失败: $e');
                              }
                              Get.toNamed(
                                Routes.me,
                                arguments: {
                                  'userId': user?.id,
                                  'fromNavBar': false,
                                  'forceRefresh': true,
                                },
                              );
                            },
                            child: CircleAvatar(
                              key: ValueKey('avatar_${user.id}_$index'),
                              radius: 24.r,
                              backgroundImage:
                                  user.avatar != null
                                      ? AssetImage(user.avatar!)
                                      : AssetImage(Images.avatar1),
                            ),
                          ),
                          SizedBox(width: 6.w),
                          Expanded(
                            child: Text(
                              '${user.nickname} just used the timer to bake the ceramic',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                          SizedBox(width: 10.w),
                          GestureDetector(
                            onTap: () {
                              // 获取用户服务
                              final userService = Get.find<UserService>();

                              // 检查登录状态并跳转
                              userService.checkLoginThenExecute(
                                loginRequiredMessage:
                                    'You need to login to use the firing timer',
                                onLoggedIn: () {
                                  Get.toNamed(Routes.firing);
                                },
                              );
                            },
                            child: Container(
                              padding: EdgeInsets.symmetric(
                                horizontal: 14.w,
                                vertical: 8.h,
                              ),
                              decoration: ShapeDecoration(
                                gradient: LinearGradient(
                                  begin: const Alignment(0.50, -0.00),
                                  end: const Alignment(0.50, 1.00),
                                  colors: [
                                    const Color(0xFF4580DD),
                                    const Color(0xFF5592F1),
                                  ],
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(28),
                                ),
                              ),
                              child: Text(
                                'To burn',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15.sp,
                                  fontWeight: FontWeight.w400,
                                ),
                              ),
                            ),
                          ),
                          SizedBox(width: 15.w),
                        ],
                      ),
                    );
                  } catch (e) {
                    print('构建卡片出错: $e');
                    return Container();
                  }
                },
                allowedSwipeDirection: AllowedSwipeDirection.only(
                  left: true,
                  right: true,
                ),
                isLoop: true,
                backCardOffset: const Offset(0, 8),
                scale: 0.96,
                threshold: 10,
                duration: const Duration(milliseconds: 350),
                padding: const EdgeInsets.all(0),
                numberOfCardsDisplayed: 3,
                onSwipe: (previousIndex, currentIndex, direction) {
                  controller.completeCardSwipe();
                  return true;
                },
              ),
            ),
          ],
        ),
      );
    });
  }

  // 陶瓷卡片轮播
  Widget _buildCeramicCardCarousel() {
    return Obx(() {
      if (controller.ceramics.isEmpty) {
        return Center(
          child: Container(
            height: (DeviceInfoUtil.isIPad() ? 339 : 304).h,
            alignment: Alignment.center,
            child: const CircularProgressIndicator(),
          ),
        );
      }

      return CarouselSlider.builder(
        itemCount: controller.ceramics.length,
        itemBuilder: (context, index, realIndex) {
          final ceramic = controller.ceramics[index];
          final user = controller.getUserById(ceramic.userId);

          // 检查是否是当前显示的卡片
          final isCurrent = controller.currentIndex.value == index;

          // 使用PageTransitionSwitcher来实现平滑的切换效果
          return Hero(
            tag: 'ceramic_${ceramic.id}',
            flightShuttleBuilder:
                (_, __, ___, ____, _____) => _buildCeramicCard(ceramic, user),
            child: AnimatedContainer(
              duration: const Duration(milliseconds: 500),
              curve: Curves.easeOutCubic,
              transform: Matrix4.identity()..scale(isCurrent ? 1.0 : 0.95),
              child: _buildCeramicCard(ceramic, user),
            ),
          );
        },
        options: CarouselOptions(
          height: (DeviceInfoUtil.isIPad() ? 339 : 304).h,
          viewportFraction: 1.0,
          enlargeCenterPage: false,
          autoPlay: controller.ceramics.length > 1, // 自动播放
          autoPlayInterval: const Duration(seconds: 5),
          autoPlayAnimationDuration: const Duration(milliseconds: 800),
          autoPlayCurve: Curves.easeInOut,
          enableInfiniteScroll: true,
          initialPage: controller.currentIndex.value,
          onPageChanged: (index, reason) {
            controller.currentIndex.value = index;

            // 更新当前用户的交互状态
            final userService = Get.find<UserService>();
            if (userService.isLoggedIn.value &&
                userService.currentUser.value?.id != null) {
              controller.updateInteractionStatus(
                userService.currentUser.value!.id!,
              );
            }
          },
          scrollPhysics: const BouncingScrollPhysics(),
        ),
      );
    });
  }

  // 陶瓷卡片
  Widget _buildCeramicCard(Ceramic ceramic, User? user) {
    return Stack(
      children: [
        Positioned.fill(child: Image.asset(Images.cardBg, fit: BoxFit.fill)),
        // 陶瓷图片
        Positioned(
          child: Padding(
            padding: EdgeInsets.only(left: 14.w, top: 12.h, right: 14.w),
            child: GestureDetector(
              onTap: () {
                Get.toNamed(Routes.detail, arguments: {'ceramic': ceramic});
              },
              child: Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child:
                    ceramic.imageUrl != null
                        ? Image.asset(ceramic.imageUrl!, fit: BoxFit.fill)
                        : Image.asset(Images.ceramic1, fit: BoxFit.fill),
              ),
            ),
          ),
        ),
        // 头像
        Positioned(
          bottom: 8.h,
          left: 14.w,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 圆角头像
                GestureDetector(
                  onTap: () {
                    // 先尝试删除已存在的MeController实例，再跳转
                    try {
                      if (Get.isRegistered<MeController>()) {
                        Get.delete<MeController>(force: true);
                      }
                    } catch (e) {
                      print('删除MeController失败: $e');
                    }
                    Get.toNamed(
                      Routes.me,
                      arguments: {
                        'userId': user?.id,
                        'fromNavBar': false,
                        'forceRefresh': true,
                      },
                    );
                  },
                  child: CircleAvatar(
                    radius: 22.r,
                    backgroundImage:
                        user?.avatar != null
                            ? AssetImage(user!.avatar!)
                            : AssetImage(Images.avatar1),
                  ),
                ),
                SizedBox(width: 10.w),
                // 昵称
                Text(
                  user?.nickname ?? 'Unknown',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w400,
                  ),
                ),
                SizedBox(width: 10.w),
                // 关注按钮
                GestureDetector(
                  onTap: () => _handleFollowAction(user),
                  child: Obx(() {
                    return Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(11.5.r),
                        color:
                            controller.isCurrentUserFollowed.value
                                ? const Color(0xFF0A3D8E)
                                : Colors.white,
                      ),
                      child: Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 3.w,
                          vertical: 3.h,
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Icon(
                              controller.isCurrentUserFollowed.value
                                  ? Icons.check
                                  : Icons.add,
                              size: 12.sp,
                              color:
                                  controller.isCurrentUserFollowed.value
                                      ? Colors.white
                                      : const Color(0xFF0A3D8E),
                            ),
                            Text(
                              controller.isCurrentUserFollowed.value
                                  ? 'followed'
                                  : 'follow',
                              style: TextStyle(
                                color:
                                    controller.isCurrentUserFollowed.value
                                        ? Colors.white
                                        : const Color(0xFF0A3D8E),
                                fontSize: 13.sp,
                                fontFamily: 'Inter',
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  }),
                ),
              ],
            ),
          ),
        ),
        // 点赞和收藏
        Positioned(
          bottom: 0.h,
          right: 9.w,
          child: Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(21.r),
            ),
            child: Padding(
              padding: EdgeInsets.symmetric(horizontal: 31.w, vertical: 9.h),
              child: Row(
                children: [
                  // 收藏按钮
                  Obx(
                    () => LikeButton(
                      size: 24.sp,
                      isLiked: controller.isCurrentCeramicFavorited.value,
                      animationDuration: Duration(milliseconds: 800),
                      circleColor: CircleColor(
                        start: Color(0xFFFF5722),
                        end: Color(0xFFFFC107),
                      ),
                      bubblesColor: BubblesColor(
                        dotPrimaryColor: Color(0xFFFF5722),
                        dotSecondaryColor: Color(0xFFFFC107),
                        dotThirdColor: Color(0xFFFF9800),
                        dotLastColor: Color(0xFFF44336),
                      ),
                      likeBuilder: (bool isLiked) {
                        return Icon(
                          isLiked
                              ? IconFontIcons.iconLikeFill
                              : IconFontIcons.iconLike,
                          color: isLiked ? Colors.red : Colors.black,
                          size: 24.sp,
                        );
                      },
                      onTap: (isLiked) async {
                        _handleInteraction(InteractionType.favorite);
                        return controller.isCurrentCeramicFavorited.value;
                      },
                    ),
                  ),
                  SizedBox(width: 27.w),
                  // 点赞按钮
                  Obx(
                    () => LikeButton(
                      size: 24.sp,
                      isLiked: controller.isCurrentCeramicLiked.value,
                      animationDuration: Duration(milliseconds: 800),
                      circleColor: CircleColor(
                        start: Color(0xFF00DDFF),
                        end: Color(0xFF0099CC),
                      ),
                      bubblesColor: BubblesColor(
                        dotPrimaryColor: Color(0xFF33B5E5),
                        dotSecondaryColor: Color(0xFF0099CC),
                        dotThirdColor: Color(0xFF00DDFF),
                        dotLastColor: Color(0xFF00AACC),
                      ),
                      likeBuilder: (bool isLiked) {
                        return Icon(
                          isLiked
                              ? IconFontIcons.iconGoodFill
                              : IconFontIcons.iconGood,
                          color: isLiked ? Colors.red : Colors.black,
                          size: 24.sp,
                        );
                      },
                      onTap: (isLiked) async {
                        _handleInteraction(InteractionType.like);
                        return controller.isCurrentCeramicLiked.value;
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 处理交互操作（点赞/收藏）
  void _handleInteraction(InteractionType type) {
    // 获取用户服务
    final userService = Get.find<UserService>();

    // 检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage:
          type == InteractionType.like
              ? 'You need to login to like this work'
              : 'You need to login to collect this work',
      onLoggedIn: () {
        // 已登录，执行相应操作
        final userId = userService.currentUser.value!.id!;

        // 检查/更新交互状态
        controller.updateInteractionStatus(userId);

        // 执行相应操作
        if (type == InteractionType.like) {
          controller.toggleLikeCeramic(userId);
        } else {
          controller.toggleFavoriteCeramic(userId);
        }
      },
    );
  }

  // 处理关注操作
  void _handleFollowAction(User? ceramicUser) {
    if (ceramicUser == null || ceramicUser.id == null) return;

    // 获取用户服务
    final userService = Get.find<UserService>();

    // 检查登录状态并执行操作
    userService.checkLoginThenExecute(
      loginRequiredMessage: 'You need to login to follow this user',
      onLoggedIn: () {
        // 已登录，执行关注操作
        final currentUserId = userService.currentUser.value!.id!;

        // 不能关注自己
        if (currentUserId == ceramicUser.id) {
          EasyLoading.showError('You cannot follow yourself');
          return;
        }

        // 检查/更新交互状态
        controller.updateInteractionStatus(currentUserId);

        // 执行关注/取消关注操作
        controller.toggleFollowUser(currentUserId, ceramicUser.id!);
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // 初始化设备类型检测
    DeviceInfoUtil.checkIsIPad();

    return GetBuilder<HomeController>(
      init: HomeController(),
      id: "home",
      builder: (_) {
        return Stack(
          children: [
            Positioned.fill(
              child: Image.asset(Images.startBg, fit: BoxFit.fill),
            ),
            SafeArea(child: _buildView()),
          ],
        );
      },
    );
  }
}
